import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_language.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

/// 安全等级评分动画组件
class SafetyScoreAnimationWidget extends StatefulWidget {
  final int? safetyScore;
  final double size;
  final double strokeWidth;

  const SafetyScoreAnimationWidget({
    super.key,
    this.safetyScore,
    this.size = 240,
    this.strokeWidth = 8,
  });

  @override
  State<SafetyScoreAnimationWidget> createState() =>
      _SafetyScoreAnimationWidgetState();
}

class _SafetyScoreAnimationWidgetState extends State<SafetyScoreAnimationWidget>
    with TickerProviderStateMixin {
  late AnimationController _progressController;
  late AnimationController _ballController;
  late Animation<double> _progressAnimation;
  late Animation<double> _ballAnimation;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  void _initAnimations() {
    // 进度动画控制器
    _progressController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );

    // 圆球动画控制器
    _ballController = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );

    // 进度动画
    _progressAnimation = Tween<double>(
      begin: 0.0,
      end: (widget.safetyScore ?? 0) / 100.0,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeInOut,
    ));

    // 圆球动画
    _ballAnimation = Tween<double>(
      begin: 0.0,
      end: (widget.safetyScore ?? 0) / 100.0,
    ).animate(CurvedAnimation(
      parent: _ballController,
      curve: Curves.easeInOut,
    ));

    // 启动动画
    _startAnimations();
  }

  void _startAnimations() {
    _progressController.forward();
    _ballController.forward();
  }

  @override
  void didUpdateWidget(SafetyScoreAnimationWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.safetyScore != widget.safetyScore) {
      _updateAnimations();
    }
  }

  void _updateAnimations() {
    _progressController.reset();
    _ballController.reset();

    _progressAnimation = Tween<double>(
      begin: 0.0,
      end: (widget.safetyScore ?? 0) / 100.0,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeInOut,
    ));

    _ballAnimation = Tween<double>(
      begin: 0.0,
      end: (widget.safetyScore ?? 0) / 100.0,
    ).animate(CurvedAnimation(
      parent: _ballController,
      curve: Curves.easeInOut,
    ));

    _startAnimations();
  }

  @override
  void dispose() {
    _progressController.dispose();
    _ballController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.size.w,
      height: widget.size.w,
      child: Stack(
        children: [
          // 外圈背景
          _buildBackgroundCircle(),
          // 背景光晕（在进度环下面）
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              return CustomPaint(
                size: Size(widget.size.w, widget.size.w),
                painter: BackgroundGlowPainter(

                  progress: _progressAnimation.value,
                ),
              );
            },
          ),
          // 进度环（覆盖在背景光晕之上）
          AnimatedBuilder(
            animation: _progressAnimation,
            builder: (context, child) {
              return CustomPaint(
                size: Size(widget.size.w, widget.size.w),
                painter: ProgressRingPainter(
                  progress: _progressAnimation.value,
                  strokeWidth: widget.strokeWidth.w,
                ),
              );
            },
          ),
          // 内圈背景和内容
          _buildInnerContent(widget.safetyScore ?? 0),
          // 动画圆球
          AnimatedBuilder(
            animation: _ballAnimation,
            builder: (context, child) {
              return _buildAnimatedBall();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildBackgroundCircle() {
    return Container(
      width: widget.size.w,
      height: widget.size.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: const Color(0xFF212327),
      ),
    );
  }

  Widget _buildInnerContent(int safetyScore) {
    return Center(
      child: Container(
        width: (widget.size * 0.5).w,
        height: (widget.size * 0.5).w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: const Color(0xFF1A1C1F),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFF00BBFF).withOpacity(0.6),
              offset: const Offset(0, 27),
              blurRadius: 43,
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              safetyScore.toString(),
              style: TextStyle(
                color: AppColor.textPrimary.withOpacity(0.94),
                fontSize: 40.sp,
                fontWeight: FontWeight.w900,
                height: 1.1,
              ),
            ),
            4.verticalSpaceFromWidth,
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                 LocaleKeys.securityLevel.tr ,
                  style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.7),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                Text(
                  _getSafetyLevelText(safetyScore),
                  style: TextStyle(
                    color: _getSafetyLevelColor(safetyScore),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            )
            // securityLevel

          ],
        ),
      ),
    );
  }

  Widget _buildAnimatedBall() {
    return AnimatedBuilder(
      animation: _ballAnimation,
      builder: (context, child) {
        final angle = _ballAnimation.value * 2 * 3.14159 - 1.5708; // 从顶部开始，-π/2
        final center = widget.size.w / 2;
        final outerRadius = (widget.size.w - widget.strokeWidth.w) / 2;
        final innerRadius = (widget.size.w * 0.5) / 2; // 内圈半径
        final ballRadius = (outerRadius + innerRadius) / 2; // 圆球位置：外圈和内圈中间

        final x = center + ballRadius * cos(angle);
        final y = center + ballRadius * sin(angle);

        return Positioned(
          left: x - 9.w,
          top: y - 9.w,
          child: Container(
            width: 18.w,
            height: 18.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              gradient: const LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Color(0xFFFFFFFF),
                  Color(0xFF9ED1FF),
                ],
              ),
              boxShadow: [
                BoxShadow(
                  color: const Color(0xFF2E51A0).withOpacity(0.36),
                  offset: const Offset(0, 1),
                  blurRadius: 2.4,
                ),
              ],
            ),
            child: Center(
              child: Container(
                width: 12.w,
                height: 12.w,
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Color(0xFF00BBFF),
                ),
              ),
            ),
          ),
        );
        
      },
    );
  }

  String _getSafetyLevelText(int score) {
    if (score >= 80) {
      return ' 高';
    } else if (score >= 60) {
      return ' 中';
    } else {
      return ' 低';
    }
  }

  Color _getSafetyLevelColor(int score) {
    if (score >= 80) {
      return const Color(0xFF00FF78); // 绿色
    } else if (score >= 60) {
      return const Color(0xFFFFB800); // 黄色
    } else {
      return const Color(0xFFED474B); // 红色
    }
  }
}

/// 背景光晕绘制器
class BackgroundGlowPainter extends CustomPainter {
  final double progress;

  BackgroundGlowPainter({required this.progress});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;

    // 绘制背景光晕
    final glowPaint = Paint()
      ..shader = SweepGradient(
        colors: [
          // Color(0xFF5B0F77).withOpacity(0.3),
          // Color(0xff2A20B5),
          // AppColor.primary,
          // // Color(0xFF5B0F77).withOpacity(0),
          // Color(0xFF5B0F77).withOpacity(0),
          // Color(0xFF5B0F77).withOpacity(0.3),
          // Colors.blue,
          // Colors.red,

          Color(0xFFFEF7F3).withOpacity(0.0),
          Color(0xFFFEF7F3).withOpacity(0.0),
          // Color(0xff096FFC).withOpacity(0.42),

          Color(0xff096FFC).withOpacity(0.42),          // AppColor.primary,
          // Color(0xFF5B0F77).withOpacity(0),
          Color(0xFFFEF7F3).withOpacity(0),
          Color(0xFFFEF7F3).withOpacity(0),

          // AppColor.safetyScoreGlowStart, // 蓝色42%透明度
          // AppColor.safetyScoreGlowEnd, // 完全透明
          // AppColor.safetyScoreGlowEnd, // 完全透明
          // AppColor.safetyScoreGlowStart, // 蓝色42%透明度
        ],
        // stops: [0.0, 0.3, 0.7, 1.0],
        startAngle: -1.5708, // 从顶部开始，-π/2
      ).createShader(Rect.fromCircle(center: center, radius: radius))
      ..style = PaintingStyle.fill;

    // 绘制背景光晕弧形，只到当前进度位置
    final sweepAngle = 2 * 3.14159 * progress;
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -1.5708, // 从顶部开始，-π/2
      sweepAngle,
      true, // useCenter = true，绘制扇形
      glowPaint,
    );
  }

  @override
  bool shouldRepaint(BackgroundGlowPainter oldDelegate) {
    return oldDelegate.progress != progress;
  }
}

/// 进度环绘制器
class ProgressRingPainter extends CustomPainter {
  final double progress;
  final double strokeWidth;

  ProgressRingPainter({
    required this.progress,
    required this.strokeWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - strokeWidth) / 2;

    // 绘制进度环
    final progressPaint = Paint()
      ..shader = SweepGradient(
        colors: [
          // AppColor.primary,

          Color(0xFF5B0F77).withOpacity(0.3),
          Color(0xff2A20B5),
          AppColor.primary,
          // Color(0xFF5B0F77).withOpacity(0),
          Color(0xFF5B0F77).withOpacity(0),
          Color(0xFF5B0F77).withOpacity(0.3),
        ],
      ).createShader(Rect.fromCircle(center: center, radius: radius))
      ..style = PaintingStyle.stroke
      ..strokeWidth = strokeWidth
      ..strokeCap = StrokeCap.round;

    // 绘制进度弧
    final sweepAngle = 2 * 3.14159 * progress;
    canvas.drawArc(
      Rect.fromCircle(center: center, radius: radius),
      -1.5708, // 从顶部开始，-π/2
      sweepAngle,
      false,
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(ProgressRingPainter oldDelegate) {
    return oldDelegate.progress != progress ||
        oldDelegate.strokeWidth != strokeWidth;
  }
}
